<template>
  <div class="product-detail-container">
    <el-page-header @back="$router.go(-1)">
      <template #content>
        <span class="text-large font-600 mr-3"> 商品详情 </span>
      </template>
    </el-page-header>

    <el-skeleton :rows="6" animated v-if="loading" />
    <el-alert v-if="error" type="error" :title="error.message" show-icon />

    <div v-if="product" class="detail-content">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-image 
            :src="apiBase + '/product_images/' + product.product_cover_image"
            fit="contain"
            class="main-image"
          />
        </el-col>

        <el-col :span="12">
          <template>
            <el-col :span="12">
              <div 
                class="image-container"
                @mouseenter="showNavigation = product.productImageList.length > 1"
                @mouseleave="showNavigation = false"
              >
                <el-image
                  :src="apiBase + '/product_images/' + (currentImage || product.product_cover_image)"
                  fit="contain"
                  class="main-image"
                />
                <div v-if="product.productImageList.length > 0" class="navigation-buttons">
                  <el-button
                    v-show="showNavigation"
                    class="nav-button left"
                    @click="handleImageSwitch(-1)"
                    icon="ArrowLeft"
                    circle
                  />
                  <el-button
                    v-show="showNavigation"
                    class="nav-button right"
                    @click="handleImageSwitch(1)"
                    icon="ArrowRight"
                    circle
                  />
                </div>
              </div>
            </el-col>
          </template>
        </el-col>

        <el-col :span="12">
          <h1 class="product-title">{{ product.product_name }}</h1>
          <el-divider />
          
          <div class="price-section">
            <span class="price-label">价格：</span>
            <span class="price-value">¥{{ product.productPrice.toFixed(2) }}</span>
          </div>

          <div class="stock-section">
            <span class="stock-label">库存：</span>
            <el-tag type="info" size="large">{{ product.productStock }}件</el-tag>
          </div>

          <div class="description-section">
            <h3>商品描述</h3>
            <el-text class="description-text">{{ product.productDescription }}</el-text>
          </div>
          <div class="quantity-section">
            <span class="quantity-label">数量：</span>
            <el-button 
              @click="quantity--" 
              :disabled="quantity <= 1">-</el-button>
            <el-input-number 
              v-model="quantity" 
              :min="1" 
              :max="product.productStock" 
              controls-position="right" 
              class="quantity-input" />
            <el-button 
              @click="quantity++" 
              :disabled="quantity >= product.productStock">+</el-button>
          </div>

          <div class="cart-actions">
            <div class="button-group">
              <el-button 
                type="primary" 
                @click="addToCart"
                :loading="addingToCart"
              >加入购物车</el-button>
              <el-button 
                type="danger" 
                @click="handleBuyNow"
                :loading="buyNowLoading"
              >立即购买</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <div v-if="isSeller" class="seller-actions">
        <el-dialog v-model="priceDialogVisible" title="编辑价格" width="30%">
  <el-form :model="priceForm" label-width="80px">
    <el-form-item label="商品价格">
      <el-input-number
        v-model="priceForm.productPrice"
        :min="0"
        :precision="2"
        controls-position="right"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="priceDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handlePriceSubmit">确认</el-button>
  </template>
</el-dialog>
<el-button type="primary" @click="openPriceDialog">编辑价格</el-button>
        <el-dialog v-model="descDialogVisible" title="编辑描述" width="60%">
  <el-form :model="descForm">
    <el-form-item>
      <el-input
        v-model="descForm.productDescription"
        type="textarea"
        :rows="6"
        placeholder="请输入商品描述"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="descDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handleDescSubmit">确认</el-button>
  </template>
</el-dialog>
<el-button type="success" @click="openDescriptionDialog">编辑描述</el-button>
      </div>
    </div>
  </div>
</template>

<script setup >
import { ref, onMounted } from 'vue';
import { getToken } from '@/utils/storage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const product = ref(null);
const loading = ref(true);
const error = ref(null);
const apiBase = ref(import.meta.env.VITE_API_BASE || '');
const isSeller = ref(false);

const quantity = ref(1);
const addingToCart = ref(false);
const buyNowLoading = ref(false);

const priceDialogVisible = ref(false);
const priceForm = ref({
  productPrice: product.value?.product_price || 0
});

const openPriceDialog = () => {
  priceForm.value.productPrice = product.value.product_price;
  priceDialogVisible.value = true;
};

const descDialogVisible = ref(false);
const descForm = ref({
  productDescription: product.value?.product_description || ''
});

const handlePriceSubmit = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }

    const { data } = await axios.put(`${apiBase.value}/product/price`, {
      productId: product.value.product_id,
      productPrice: priceForm.value.productPrice
    }, {
      headers: { Authorization: `Bearer  ${token}` }
    });

    product.value.product_price = priceForm.value.productPrice;
    ElMessage.success(data);
    priceDialogVisible.value = false;
  } catch (err) {
    ElMessage.error(err.response?.data || '修改失败');
  }
};

const handleDescSubmit = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }

    const { data } = await axios.put(`${apiBase.value}/product/description`, {
      productId: product.value.product_id,
      productDescription: descForm.value.productDescription
    }, {
      headers: { Authorization: `Bearer  ${token}` }
    });

    product.value.product_description = descForm.value.productDescription;
    ElMessage.success(data);
    descDialogVisible.value = false;
  } catch (err) {
    ElMessage.error(err.response?.data || '修改失败');
  }
};

const addToCart = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }

    const { data } = await axios.post(`${apiBase.value}/cart`, {
      productId: product.value.product_id,
      quantity: quantity.value,
      selected: true
    }, {
      headers: { Authorization: `Bearer  ${token}` }
    });

    ElMessageBox.confirm(
      data,
      '操作成功',
      {
        confirmButtonText: '查看购物车',
        cancelButtonText: '继续购物',
        type: 'success'
      }
    ).then(() => {
      router.push('/cart');
    }).catch(() => {})
  } catch (err) {
    ElMessage.error(err.response?.data || '加入购物车失败');
  }
};

const openDescriptionDialog = () => {
  descForm.value.productDescription = product.value.product_description;
  descDialogVisible.value = true;
};

const getUserRole = async () => {
  try {
    const { data: userData } = await axios.get(`${apiBase.value}/user`, {
  headers: { Authorization: `Bearer  ${getToken()}` }
});
    const isSellerType = ['seller', 'both'].includes(userData.user_type?.toLowerCase());
    
    const { data: productData } = await axios.get(`${apiBase.value}/product/${route.params.productId}`, {
  headers: { Authorization: `Bearer  ${getToken()}` }
});
    const isSameSeller = userData.user_id === productData.seller_id;

    isSeller.value = isSellerType && isSameSeller;
  } catch (err) {
    console.error('获取用户信息失败:', err);
  }
};

onMounted(async () => {
  await getUserRole();
  try {
    const productId = route.params.productId;
    const { data } = await axios.get(`${apiBase.value}/product/${productId}`);
    product.value = {
      ...data,
      seller_id: data.seller_id,
      product_cover_image: data.product_cover_image?.replace(/\\/g, '/') || ''
    };
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
});

const handleBuyNow = async () => {
  try {
   // 检查配送地址
   const { data: addressData } = await axios.get(`${apiBase.value}/user/delivery`, {
      headers: { Authorization: `Bearer ${getToken()}` }
    });

    // 直接使用返回数据
    console.log('地址接口返回数据:', addressData);

    // 通用数据存在检查
    const hasAddress = addressData && 
      (Array.isArray(addressData) ? 
        addressData.length > 0 : 
        Object.keys(addressData).length > 0);

    if (!hasAddress) {
      await ElMessageBox.confirm('您还没有收货地址，是否现在去添加？', '提示', {
        confirmButtonText: '去添加',
        cancelButtonText: '取消',
        type: 'warning'
      });
      return router.push('/address-management');
    }
    buyNowLoading.value = true;
    
    // 获取配送信息
    const deliveryRes = await axios.get(`${apiBase.value}/user/delivery`, {
      headers: { Authorization: `Bearer ${getToken()}` }
    })
    
    // 创建订单
    const orderRes = await axios.post(`${apiBase.value}/order`, {
      productId: product.value.product_id,
      quantity: quantity.value,
      deliveryInfo: deliveryRes.data
    }, {
      headers: { Authorization: `Bearer ${getToken()}` }
    })

    // 跳转支付页面
    router.push({
      path: '/payment',
      query: {
        orderId: orderRes.data.order_id,
        productName: product.value.product_name,
        productPrice: product.value.product_price,
        totalAmount: orderRes.data.order_total_amount,
        quantity: quantity.value,
        productImage: product.value.product_cover_image
      }
    })
  } catch (err) {
    console.error('立即购买请求失败:', err)
    ElMessage.error('创建订单失败：' + (err.response?.data?.message || err.message))
  } finally {
    buyNowLoading.value = false
  }
}
</script>



<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.main-image {
  width: 100%;
  height: 500px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-title {
  font-size: 28px;
  margin-bottom: 20px;
}

.price-section {
  margin: 30px 0;
}

.price-value {
  font-size: 32px;
  color: #f56c6c;
  font-weight: bold;
}

.stock-section {
  margin: 30px 0;
}

.description-section {
  margin-top: 40px;
}

.description-text {
  font-size: 16px;
  line-height: 1.8;
  white-space: pre-wrap;

}
.quantity-input ::v-deep .el-input-number__increase,
.quantity-input ::v-deep .el-input-number__decrease {
  display: none !important;
}
.quantity-input ::v-deep .el-input__wrapper {
  padding-left: 10px;
  padding-right: 10px;
}
</style>








